package controller.auth;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.auth.Resources;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import service.auth.ResourcesService;
import core.base.controller.BaseSpringController;
import core.base.controller.PageHelper;
import core.base.exception.ValidateException;
import core.base.page.Page;
import core.base.page.PageRequest;
import core.util.ParamUtil;
import core.util.StringUtil;

@Controller("admin.auth.ResourcesAdminController")
@RequestMapping("/admin/auth/res")
public class ResourcesAdminController extends BaseSpringController {

	private String queryView = "admin/res/query";
	private String incListView = "admin/res/inclist";
	private String addView = "admin/res/resadd";
	private String viewView = "admin/res/resview";
	private String redirectView = "admin/common/redirect";
	
	@Autowired
	@Qualifier("auth.ResourcesService")
	private ResourcesService resourcesService;
	
	@RequestMapping("query.htm")
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView(queryView);
	}
	
	@RequestMapping("inc_list.htm")
	public ModelAndView incList(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		
		PageRequest<Map> pageReq = new PageRequest<Map>();
		HashMap<String, Object> filters = new HashMap<String, Object>();
		StringBuffer params = new StringBuffer();
		if(!StringUtil.isBlank(request.getParameter("resName"))){
			filters.put("resName", "%" + request.getParameter("resName") + "%");
			params.append("&resName=" + request.getParameter("resName"));
		}
		if(!StringUtil.isBlank(request.getParameter("resCode"))){
			filters.put("resCode", request.getParameter("resCode"));
			params.append("&resCode=" + request.getParameter("resCode"));
		}
		if(!StringUtil.isBlank(request.getParameter("resType"))){
			filters.put("resType", request.getParameter("resType"));
			params.append("&resType=" + request.getParameter("resType"));
		}
		if(!StringUtil.isBlank(request.getParameter("resLink"))){
			filters.put("resLink", "%" + request.getParameter("resLink") + "%");
			params.append("&resLink=" + request.getParameter("resLink"));
		}
		
		PageHelper pageHelper = new PageHelper(request);
		// 获取请求的显示的页数,如为空,则取默认第1页
		int pageNum = ParamUtil.getInt(request, "pageNum", 1);
		// 设置默认每页显示记录数
		int pageSize = pageHelper.doCustomPerPage(DEFAULT_PAGESIZE);
		
		pageReq.setFilters(filters);
		pageReq.setPageNumber(pageNum);
		pageReq.setPageSize(pageSize);
		
		Page<Resources> page = resourcesService.queryForPage(pageReq);
		popPageInfo(page, modelMap);
		if(params.length()>0){
			page.setParamName(params.substring(1, params.length()));
		}		
		String pageBreakStr = pageHelper.getPageBreakStr(page);
		modelMap.put("pageBreakStr", pageBreakStr);
		return new ModelAndView(incListView).addAllObjects(modelMap);
	}

	@RequestMapping("edit.htm")
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		return new ModelAndView(addView).addAllObjects(modelMap);
	}

	@RequestMapping("editsave.htm")
	public ModelAndView editsave(HttpServletRequest request, HttpServletResponse response) {
		Resources model = null;
		try {
			model = getModelFromRequest(request);
		} catch (ValidateException e) {
			super.saveError(request, e.getMessage());
		}
		resourcesService.insert(model);
		String redirecturl = request.getContextPath() + "/admin/auth/res/query.htm";
		return new ModelAndView(redirectView)
			.addObject("redirecturl", redirecturl)
			.addObject("msg", "保存成功！");
	}

	@RequestMapping("add.htm")
	public ModelAndView add(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		return new ModelAndView(addView).addAllObjects(modelMap);
	}

	@RequestMapping("addsave.htm")
	public ModelAndView addSave(HttpServletRequest request, HttpServletResponse response) {
		Resources model = null;
		try {
			model = getModelFromRequest(request);
		} catch (ValidateException e) {
			super.saveError(request, e.getMessage());
		}
		resourcesService.insert(model);
		String redirecturl = request.getContextPath() + "/admin/auth/res/query.htm";
		String continueurl = request.getContextPath() + "/admin/auth/res/add.htm";
		return new ModelAndView(redirectView)
			.addObject("redirecturl", redirecturl)
			.addObject("continueurl", continueurl)
			.addObject("msg", "保存成功！");
	}
	
	public Resources getModelFromRequest(HttpServletRequest request) throws ValidateException{
		Resources model = new Resources();
		model.setResCode(request.getParameter("resCode"));
		model.setResName(request.getParameter("resName"));
		model.setResDesc(request.getParameter("resDesc"));
		model.setResLink(request.getParameter("resLink"));
		model.setResType(request.getParameter("resType"));
		
		if(StringUtil.isBlank(model.getResCode())){
			super.saveError(request, "");
		}
		
		model.setPriority(ParamUtil.getInt(request, "priority", 0));
		if ("1".equals(StringUtil.defaultStringIfBlank(request.getParameter("enabled"),"1"))) {
			model.setEnabled(1);
		}else{
			model.setEnabled(0);
		}
		if ("1".equals(StringUtil.defaultStringIfBlank(request.getParameter("issys"),"1"))) {
			model.setIssys(1);
		}else{
			model.setIssys(0);
		}
		// TODO check code是否已存在; 检查数据格式
		
		return model;
	}
	
	/**
	 * 批量删除
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("delbatch.htm")
	public ModelAndView delbatch(HttpServletRequest request, HttpServletResponse response) {
		//删除数据
		Long[] ids = ParamUtil.getLongAsArray(request, "checkValue", new Long[0]);
		
		resourcesService.deleteBatch(ids);
		StringBuffer buf = new StringBuffer();
		buf.append("{result:'OK'}");
		try {
			response.getWriter().print(buf.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		//String redirecturl = request.getContextPath() + "/admin/auth/res/query.htm";
		//return new ModelAndView(redirectView).addObject("redirecturl", redirecturl);
		return null;
	}

	@RequestMapping("view.htm")
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		Long id = Long.valueOf(request.getParameter("id"));
		Resources res = resourcesService.getById(id);
		modelMap.put("data", res);
		return new ModelAndView(viewView).addAllObjects(modelMap);
	}

	public void setResourcesService(ResourcesService resourcesService) {
		this.resourcesService = resourcesService;
	}
	
	
}
